import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import axios from 'axios'
import request from '@/http2';
import config from '@/config';
Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/loading',
    name: 'Loading',
    component: () => import( /* webpackChunkName: "about" */ '../views/Loading.vue')
  },
  {
    path: '/bindphone',
    name: 'UserBIndPhone',
    component: () => import( /* webpackChunkName: "about" */ '../views/UserBIndPhone.vue')
  },
  {
    path: '/map',
    name: 'map',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import( /* webpackChunkName: "about" */ '../views/Map.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import( /* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})


/** 去掉微信授权的code参数 */
function deleteCodeQuery(url) {
  const newUrl = url.replace(/(^|&)code=([^&]*)(&|$)/, "&");
  return newUrl.endsWith("&") ? newUrl.substring(0, newUrl.length - 1) : newUrl;
}

/**
 * 处理url 去掉微信返回时带的参数
 */
function handleWXbackUrl() {
  const w = location.href.indexOf("?");
  const j = location.href.indexOf("#");
  let href = window.location.href;
  let url;
  if (w !== -1 && j > w) {
    href =
      location.href.substr(0, w) +
      location.href.substr(j, location.href.length);
    url = href;
  } else {
    url = location.href;
  }
  return url;
}

function getQueryString() {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  const params = {};
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    params[pair[0]] = decodeURIComponent(pair[1]);
  }
  return params;
}

/**
 * 微信授权
 * @param weChatAppId weChatAppId
 */
function auth(weChatAppId) {
  const callbackUrl = handleWXbackUrl();
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${weChatAppId}&redirect_uri=${encodeURIComponent(
    callbackUrl
  )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  const result = getQueryString();
  if (result.code && !sessionStorage.getItem("flag")) {
    return result.code;
  } else {
    sessionStorage.removeItem("flag");
  }
  window.location.replace(deleteCodeQuery(url));
}

// 判断是否在微信
function isWeChat() {
  let ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}


function getToken(code) {
  let weChatId = localStorage.getItem('weChatId')
  return axios.get(`${config.requestUrl}/cqliving-boot-act-server/act/detail?actCode=8TSCZp2dCiyevQGldk0L3xmmyP55uO&code=${code}&weChatId=${weChatId}&appId=1&registSourceType=act`)
}

function getSid() {
  return request.get('/u/ns');
}

function isSid(next) {
  let sid = localStorage.getItem('sessionId');
  let token = localStorage.getItem('token');
  let userinfo = localStorage.getItem('userinfo');
  let result = getQueryString();
  if (sid == 'undefined' || !sid) {
    getSid().then((msg) => {
      localStorage.setItem('sessionId', msg.data.id);
      if (token && !userinfo) {
        Login(token, next);
      } else {
        if (result.code) {
          window.location.replace(`${window.location.origin}${window.location.pathname}`)
        } else {
          next();
        }
      }
    }).catch((err) => {
      next()
    })
  } else if (sid && token && !userinfo) {
    Login(token, next);
  } else {
    if (result.code) {
      window.location.replace(`${window.location.origin}${window.location.pathname}`)
    } else {
      next();
    }
  }
}

function routerNext(next) {
  let weChatAppId = localStorage.getItem('weChatAppId');
  let isregister = localStorage.getItem('isregister');
  let result = getQueryString();
  if (!isregister) {
    let code = auth(weChatAppId);
    if (code) {
      getToken(code).then((res) => {
        console.log(JSON.stringify(res.data.data));
        if (res.data.code == -1) {
          console.log('用户未注册')
          localStorage.setItem('isregister', 'flase');
        } else {
          localStorage.setItem('isregister', 'true');
          console.log('用户已注册')
          sessionStorage.setItem(
            "token_openId",
            `${res.data.data.token}^_^${res.data.data.openId}`
          );
          localStorage.setItem('token', res.data.data.token);
        }
        isSid(next);
      });
    } else {
      isSid(next);
    }
  } else {
    isSid(next);
  }
}

function Login(token, next) {
  request.post('/u/login', {
    token: token,
  }).then((res) => {
    localStorage.setItem("userinfo", JSON.stringify(res.data));
    let result = getQueryString();
    if (result.code) {
      window.location.replace(`${window.location.origin}${window.location.pathname}`)
    } else {
      next();
    }
  }).catch((err) => {
    Vue.prototype.$toast('登录异常');
    localStorage.removeItem('token');
    next('/');
  })
}

export const funcUrlDel = name => {
  const arrName = name.split(",");
  var loca = window.location;
  var query = loca.search.substr(1);

  let obj = {};
  let arr = query.split("&");
  let url = "";
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i].split("=");
    obj[arr[i][0]] = arr[i][1];

    if (i === arr.length - 1) {
      for (let k = 0; k < arrName.length; k++) {
        if (query.indexOf(arrName[k]) > -1) {
          delete obj[arrName[k]];
        }
      }
    }
  }

  var baseUrl =
    JSON.stringify(obj) === "{}" ? loca.pathname : loca.pathname + "?";
  url =
    baseUrl +
    JSON.stringify(obj)
    .replace(/[\"\{\}]/g, "")
    .replace(/\:/g, "=")
    .replace(/\,/g, "&");
  return url;
};


// 活动详情url
let actUrl = `${config.requestUrl}/cqliving-boot-act-server/act/detail?actCode=8TSCZp2dCiyevQGldk0L3xmmyP55uO&registSourceType=act`


router.beforeEach((to, from, next) => {
  let weChatAppId = localStorage.getItem('weChatAppId');
  let token = localStorage.getItem('token');
  let sid = localStorage.getItem('sessionId');
  let userinfo = localStorage.getItem('userinfo');
  let isregister = localStorage.getItem('isregister');
  let allImagesLoaded = localStorage.getItem('allImagesLoaded');
  if (!allImagesLoaded && to.path != '/loading') {
    next('/loading');
  } else if (to.path == '/bindphone' || to.path == '/loading') {
    next();
  } else if (!weChatAppId) {
    axios.get(actUrl).then(res => {
      localStorage.setItem('weChatAppId', res.data.data.weChatAppId);
      localStorage.setItem('weChatId', res.data.data.weChatId);
      localStorage.setItem('shareObj', JSON.stringify({
        shareTitle: res.data.data.shareTitle,
        shareSummary: res.data.data.shareSummary,
        shareImgUrl: res.data.data.shareImgUrl,
      }))
      routerNext(next)
    })
  } else if (!token) {
    routerNext(next);
  } else if (!userinfo && token && sid) {
    Login(token, next);
  } else {
    isSid(next);
  }

})

export default router